﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace SNSComponent.SNSProvider
{
    public abstract class BaseProvider : IProvider
    {
        public string ProviderName { get; protected set; }

        public bool IsAuthed { get; protected set; }

        public BaseProvider(string providerName)
        {
            this.ProviderName = providerName;
            Load();
        }

        public abstract Task<ResultData> ShareStatus(string conetxt);

        public abstract Task<ResultData> ShareStatus(string context, Stream image);

        public abstract Task<ResultData> ShareStatus(string context, Uri imageUri);

        public abstract Task<ResultData> ShareStatusWithLocation(string conetxt);

        public abstract Task<ResultData> ShareStatusWithLocation(string context, Stream image);

        public abstract Task<ResultData> ShareStatusWithLocation(string context, Uri imageUri);

        public abstract void GetToken();

        public event EventHandler<ResultDataEventArgs> GetTokenComplated;

        protected virtual void OnTokenComplated(ResultData resultData)
        {
            Utiltiy.SafeRaise.Raise(GetTokenComplated, this, new ResultDataEventArgs(resultData));
        }

        public event EventHandler TokenChanged;

        public virtual void OnTokenChanged()
        {
            Save();
            Utiltiy.SafeRaise.Raise(TokenChanged, this);
        }

        protected abstract void LoadFromeStrem(Stream localData);

        protected abstract Stream ToStream();

        public void Save()
        {
            using (Stream stream = ToStream())
            {
                stream.Seek(0, SeekOrigin.Begin);
                SNSComponent.LocalData.LocalDataProvider.Save(stream, this.ProviderName);
            }
            
        }

        private  void Load()
        {
            using (Stream stream = SNSComponent.LocalData.LocalDataProvider.Read(this.ProviderName))
            {
                LoadFromeStrem(stream);
            }
        }

        public virtual void CleanToken()
        {
            this.IsAuthed = false;
            SNSComponent.LocalData.LocalDataProvider.DeleteFile(this.ProviderName);
        }

    }
}
